import { useState, useEffect } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import { ArrowLeft, Calendar, Flag, Folder, Tag, Bot, Plus, Trash2, Circle, CheckCircle } from 'lucide-react'
import { aiAPI, taskAPI } from '../services/api'
// TimeUtils导入已移除，当前版本暂不使用

export default function TaskCreatePage() {
  const navigate = useNavigate()
  const location = useLocation()
  const [task, setTask] = useState({
    title: '',
    description: '',
    dueDate: '',
    dueTime: '', // 新增：时间字段 "HH:mm" 格式
    reminderMinutes: 30, // 新增：提醒间隔（分钟）
    priority: 'P2' as 'P0' | 'P1' | 'P2' | 'P3',
    category: 'work' as 'work' | 'personal' | 'learning' | 'health' | 'other',
    tags: [] as string[],
    notes: '',
    isRecurring: false,
    recurringType: 'daily' as 'daily' | 'weekly' | 'monthly' | 'yearly',
    recurringPattern: '',
    status: 'todo' as 'todo' | 'in_progress' | 'review' | 'done'
  })
  
  // 极简模式状态
  const [isMinimalMode, setIsMinimalMode] = useState(true)
  const [aiSuggestions, setAiSuggestions] = useState<Array<{
    type: 'recurring' | 'priority' | 'category' | 'reminder' | 'time'
    message: string
    action: () => void
    accepted?: boolean
  }>>([])
  const [showTimeSelector, setShowTimeSelector] = useState(false)
  const [showCustomDatePicker, setShowCustomDatePicker] = useState(false)
  
  // 处理从其他页面传来的预设数据
  useEffect(() => {
    const state = location.state as { 
      defaultStatus?: string
      template?: {
        title?: string
        description?: string
        priority?: string
        category?: string
        tags?: string[]
        notes?: string
        recurringType?: string
        recurringPattern?: string
      }
    } | null
    
    if (state?.defaultStatus) {
      setTask(prev => ({
        ...prev,
        status: state.defaultStatus as 'todo' | 'in_progress' | 'review' | 'done'
      }))
    }
    
    // 处理模板数据（复制任务时使用）
    if (state?.template) {
      const template = state.template
      setTask(prev => ({
        ...prev,
        title: template.title || prev.title,
        description: template.description || prev.description,
        priority: (template.priority as any) || prev.priority,
        category: (template.category as any) || prev.category,
        tags: template.tags || prev.tags,
        notes: template.notes || prev.notes,
        isRecurring: !!template.recurringType,
        recurringType: (template.recurringType as any) || prev.recurringType,
        recurringPattern: template.recurringPattern || prev.recurringPattern
      }))
      
      // 如果是重复任务模板，展开详情面板
      if (template.recurringType) {
        setShowDetails(true)
      }
    }
  }, [location.state])
  const [showDetails, setShowDetails] = useState(false)
  const [showAIDecompose, setShowAIDecompose] = useState(false)
  const [subtasks, setSubtasks] = useState<Array<{title: string, completed: boolean}>>([])
  const [newSubtaskTitle, setNewSubtaskTitle] = useState('')
  const [isAIParsing, setIsAIParsing] = useState(false)
  const [aiParsingStatus, setAiParsingStatus] = useState<string>('')

  // 将任意日期字符串规范为 input 可用的 YYYY-MM-DD（本地时区）
  const normalizeDateInput = (dateStr: string | null | undefined): string => {
    if (!dateStr) return ''
    // 已是 YYYY-MM-DD 直接返回
    if (/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) return dateStr
    const d = new Date(dateStr)
    if (isNaN(d.getTime())) return ''
    const y = d.getFullYear()
    const m = String(d.getMonth() + 1).padStart(2, '0')
    const day = String(d.getDate()).padStart(2, '0')
    return `${y}-${m}-${day}`
  }

  // 保留占位以便后续需要格式化展示（当前未使用）

  // 重复模式中文化函数
  const getRecurringPatternLabel = (pattern: string | null | undefined) => {
    if (!pattern || typeof pattern !== 'string') return ''
    
    const patternMap: { [key: string]: string } = {
      'every_day': '每天',
      'every_week': '每周',
      'every_month': '每月',
      'every_year': '每年',
      'every_monday': '每周一',
      'every_tuesday': '每周二',
      'every_wednesday': '每周三',
      'every_thursday': '每周四',
      'every_friday': '每周五',
      'every_saturday': '每周六',
      'every_sunday': '每周日',
      'every_weekday': '每个工作日',
      'every_weekend': '每个周末',
      'every_2_days': '每两天',
      'every_3_days': '每三天',
      'every_2_weeks': '每两周',
      'every_month_on_1st': '每月1号',
      'every_month_on_15th': '每月15号',
      'every_month_last_day': '每月最后一天',
      'every_quarter': '每季度',
      'every_6_months': '每半年'
    }

    if (patternMap[pattern]) {
      return patternMap[pattern]
    }

    // 动态解析
    if (pattern.startsWith('every_')) {
      const daysMatch = pattern.match(/every_(\d+)_days?/)
      if (daysMatch) return `每${daysMatch[1]}天`

      const weeksMatch = pattern.match(/every_(\d+)_weeks?/)
      if (weeksMatch) return `每${weeksMatch[1]}周`

      const monthsMatch = pattern.match(/every_(\d+)_months?/)
      if (monthsMatch) return `每${monthsMatch[1]}个月`

      const yearsMatch = pattern.match(/every_(\d+)_years?/)
      if (yearsMatch) return `每${yearsMatch[1]}年`
    }

    return pattern
  }

  const addSubtask = () => {
    if (!newSubtaskTitle.trim()) return
    setSubtasks([...subtasks, { title: newSubtaskTitle.trim(), completed: false }])
    setNewSubtaskTitle('')
  }

  const removeSubtask = (index: number) => {
    setSubtasks(subtasks.filter((_, i) => i !== index))
  }

  const toggleSubtask = (index: number) => {
    setSubtasks(subtasks.map((st, i) => 
      i === index ? { ...st, completed: !st.completed } : st
    ))
  }

  const handleSave = async () => {
    if (!task.title.trim()) return
    
    try {
      // 合并日期和时间为完整的时间戳
      let fullDateTime = task.dueDate
      if (task.dueDate && task.dueTime) {
        // 如果同时有日期和时间，需要正确处理时区
        // 创建本地时间对象，然后转换为UTC时间
        const [hours, minutes] = task.dueTime.split(':').map(Number)
        const localDateTime = new Date(task.dueDate)
        localDateTime.setHours(hours, minutes, 0, 0)
        fullDateTime = localDateTime.toISOString()
      } else if (task.dueDate) {
        // 只有日期，保持原格式
        fullDateTime = task.dueDate
      }
      
      // 准备任务数据
      const taskData = {
        title: task.title,
        description: task.description,
        dueDate: fullDateTime, // 使用合并后的完整时间
        reminderMinutes: task.reminderMinutes, // 提醒间隔
        priority: task.priority,
        category: task.category,
        tags: task.tags,
        notes: task.notes,
        completed: false,
        subtasks: subtasks,
        isRecurring: task.isRecurring,
        recurringType: task.isRecurring ? task.recurringType : null,
        recurringPattern: task.isRecurring ? task.recurringPattern : null,
        status: task.status,
        boardPosition: 0
      }
      
      // 调用API保存任务
      const result = await taskAPI.createTask(taskData)
      if (result.id) {
        console.log('任务保存成功:', result)
        // 保存成功后返回主页
        navigate('/')
      } else {
        console.error('任务保存失败:', result.message)
        alert('任务保存失败，请重试')
      }
    } catch (error) {
      console.error('保存任务时出错:', error)
      alert('保存任务时出错，请重试')
    }
  }

  // 轻量级本地解析（仅处理时间，其他交给AI）
  const localSmartParse = (text: string) => {
    const now = new Date()
    const today = now.toISOString().split('T')[0]
    
    const result = {
      dueDate: null as string | null,
      dueTime: '' as string,
      priority: 'P2' as 'P0' | 'P1' | 'P2' | 'P3',
      category: 'work' as 'work' | 'personal' | 'learning' | 'health' | 'other',
      tags: [] as string[],
      notes: ''
    }
    
    // 时间解析（本地处理的核心优势）
    const timeMatch = text.match(/(上午|下午|晚上|早上|中午)?\s*(\d{1,2})(点|时|:)\s*(半|(\d{1,2})(分?)|(\d{2}))?/)
    if (timeMatch) {
      const timePrefix = timeMatch[1]
      let hour = parseInt(timeMatch[2])
      let minute = 0
      
      if (timeMatch[4] === '半') {
        minute = 30
      } else if (timeMatch[5]) {
        minute = parseInt(timeMatch[5])
      } else if (timeMatch[7]) {
        minute = parseInt(timeMatch[7])
      }
      
      if (timePrefix === '下午' || timePrefix === '晚上') {
        if (hour < 12) hour += 12
      } else if (timePrefix === '上午' && hour === 12) {
        hour = 0
      }
      
      if (!timePrefix && hour < 8 && hour !== 0) {
        hour += 12
      }
      
      result.dueTime = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`
    }
    
    // 基础日期解析（快速响应）
    if (/(今天|现在)/.test(text) || (timeMatch && !/(明天|后天|下周)/.test(text))) {
      result.dueDate = today
    } else if (/明天/.test(text)) {
      const tomorrow = new Date(now)
      tomorrow.setDate(now.getDate() + 1)
      result.dueDate = tomorrow.toISOString().split('T')[0]
    } else if (/大后天/.test(text)) {
      const threeDaysLater = new Date(now)
      threeDaysLater.setDate(now.getDate() + 3)
      result.dueDate = threeDaysLater.toISOString().split('T')[0]
    } else if (/后天/.test(text)) {
      const dayAfterTomorrow = new Date(now)
      dayAfterTomorrow.setDate(now.getDate() + 2)
      result.dueDate = dayAfterTomorrow.toISOString().split('T')[0]
    }
    
    // 优先级、分类、标签等完全交给AI智能处理
    return result
  }

  // 快速日期设置
  const setQuickDate = (type: 'today' | 'tomorrow' | 'week' | 'custom') => {
    const now = new Date()
    let targetDate = ''
    
    switch (type) {
      case 'today':
        targetDate = now.toISOString().split('T')[0]
        break
      case 'tomorrow':
        const tomorrow = new Date(now)
        tomorrow.setDate(now.getDate() + 1)
        targetDate = tomorrow.toISOString().split('T')[0]
        break
      case 'week':
        const nextWeek = new Date(now)
        nextWeek.setDate(now.getDate() + 7)
        targetDate = nextWeek.toISOString().split('T')[0]
        break
      case 'custom':
        // 触发日期选择器
        return
    }
    
    setTask(prev => ({ ...prev, dueDate: targetDate }))
  }

  // 生成AI建议
  const generateAISuggestions = (parsedData: any) => {
    const suggestions: typeof aiSuggestions = []
    
    // 智能重复任务建议 - 基于AI解析结果，而非硬匹配
    if (parsedData.isRecurring && !task.isRecurring) {
      suggestions.push({
        type: 'recurring',
        message: `AI识别这可能是重复任务：${parsedData.recurringPattern || '定期执行'}`,
        action: () => {
          setTask(prev => ({ 
            ...prev, 
            isRecurring: true, 
            recurringType: parsedData.recurringType || 'daily',
            recurringPattern: parsedData.recurringPattern || ''
          }))
          console.log('已设置为重复任务:', parsedData.recurringType)
        }
      })
    }
    
    // 智能优先级建议 - 基于AI解析结果
    if (parsedData.priority && parsedData.priority !== task.priority && parsedData.priority === 'P1') {
      suggestions.push({
        type: 'priority',
        message: 'AI识别这是高优先级任务，建议调整优先级',
        action: () => {
          setTask(prev => ({ ...prev, priority: parsedData.priority }))
          console.log('已调整为AI建议的优先级:', parsedData.priority)
        }
      })
    }
    
    // 时间建议
    if (parsedData.dueTime && !task.dueTime) {
      suggestions.push({
        type: 'time',
        message: `AI解析到时间 ${parsedData.dueTime}，建议设置具体时间`,
        action: () => {
          setTask(prev => ({ ...prev, dueTime: parsedData.dueTime }))
          setShowTimeSelector(true)
          console.log('已设置具体时间:', parsedData.dueTime)
        }
      })
    }
    
    // 智能分类建议 - 基于AI解析结果
    if (parsedData.category && parsedData.category !== task.category) {
      const categoryLabels = {
        work: '工作',
        personal: '个人',
        learning: '学习', 
        health: '健康',
        other: '其他'
      }
      
      suggestions.push({
        type: 'category',
        message: `AI建议将此任务归类为${categoryLabels[parsedData.category as keyof typeof categoryLabels] || parsedData.category}任务`,
        action: () => {
          setTask(prev => ({ ...prev, category: parsedData.category }))
          console.log('已调整为AI建议的分类:', parsedData.category)
        }
      })
    }
    
    // 智能提醒间隔建议 - 基于AI解析和任务特征
    if (parsedData.dueDate && task.reminderMinutes === 30) {
      let suggestedMinutes = 30
      let reason = ''
      
      // 基于AI识别的优先级调整提醒间隔
      if (parsedData.priority === 'P1') {
        suggestedMinutes = 60
        reason = '高优先级任务建议提前1小时提醒'
      } else if (parsedData.category === 'work' && parsedData.tags?.some((tag: string) => /会议|开会/.test(tag))) {
        suggestedMinutes = 15
        reason = '会议类任务建议提前15分钟提醒'
      } else if (parsedData.category === 'personal' && parsedData.tags?.some((tag: string) => /生日|聚会/.test(tag))) {
        suggestedMinutes = 120
        reason = '社交活动建议提前2小时提醒，便于准备'
      }
      
      if (suggestedMinutes !== 30) {
        suggestions.push({
          type: 'reminder',
          message: reason,
          action: () => {
            setTask(prev => ({ ...prev, reminderMinutes: suggestedMinutes }))
            console.log('已设置AI建议的提醒间隔:', suggestedMinutes, '分钟')
          }
        })
      }
    }
    
    setAiSuggestions(suggestions)
  }

  const handleSmartParse = async () => {
    if (!task.title.trim()) return
    
    setIsAIParsing(true)
    setAiParsingStatus('正在分析任务内容...')
    
    try {
      const result = await aiAPI.smartParse(task.title)
      if (result.success && result.result) {
        const aiResult = result.result
        
        // 如果AI没有解析出时间，使用本地解析作为补充
        const localResult = localSmartParse(task.title)
        
        const updatedTask = {
          // 统一将日期规范为 YYYY-MM-DD，避免界面出现 ISO 字符串
          dueDate: normalizeDateInput(aiResult.dueDate) || localResult.dueDate || task.dueDate,
          // 优先使用AI返回的dueTime，其次用本地解析
          dueTime: (aiResult.dueTime as string) || localResult.dueTime || task.dueTime,
          priority: (aiResult.priority as any) || localResult.priority || task.priority,
          category: (aiResult.category as any) || localResult.category || task.category,
          tags: aiResult.tags?.length > 0 ? aiResult.tags : localResult.tags || task.tags,
          notes: aiResult.notes || localResult.notes || task.notes
        }
        
        setTask(prev => ({
          ...prev,
          ...updatedTask
        }))
        
        // 生成AI建议
        generateAISuggestions({ ...aiResult, ...localResult })
        
        // 在极简模式下不自动展开详情
        if (!isMinimalMode) {
          setShowDetails(true)
        }
        
        setAiParsingStatus('解析完成！已为您智能填充任务信息')
        setTimeout(() => setAiParsingStatus(''), 3000)
      } else {
        console.warn('AI智能解析失败，使用本地解析:', result.message)
        // AI失败时，完全使用本地解析
        const localResult = localSmartParse(task.title)
        setTask(prev => ({
          ...prev,
          dueDate: localResult.dueDate || prev.dueDate,
          dueTime: localResult.dueTime || prev.dueTime,
          priority: localResult.priority || prev.priority,
          category: localResult.category || prev.category,
          tags: localResult.tags || prev.tags,
          notes: localResult.notes || prev.notes
        }))
        
        generateAISuggestions(localResult)
        setAiParsingStatus('使用本地解析完成')
        setTimeout(() => setAiParsingStatus(''), 3000)
      }
    } catch (error) {
      console.error('AI智能解析出错，使用本地解析:', error)
      // 出错时使用本地解析
      const localResult = localSmartParse(task.title)
      setTask(prev => ({
        ...prev,
        dueDate: localResult.dueDate || prev.dueDate,
        dueTime: localResult.dueTime || prev.dueTime,
        priority: localResult.priority || prev.priority,
        category: localResult.category || prev.category,
        tags: localResult.tags || prev.tags,
        notes: localResult.notes || prev.notes
      }))
      
      generateAISuggestions(localResult)
      setAiParsingStatus('解析完成（本地模式）')
      setTimeout(() => setAiParsingStatus(''), 3000)
    } finally {
      setIsAIParsing(false)
    }
  }

  // 处理回车键触发AI解析
  const handleKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter' && !isAIParsing && task.title.trim()) {
      e.preventDefault()
      handleSmartParse()
    }
  }

  // 接受AI建议
  const acceptSuggestion = (index: number) => {
    const suggestion = aiSuggestions[index]
    console.log('应用AI建议:', suggestion.type, suggestion.message)
    
    // 执行建议的操作
    suggestion.action()
    
    // 立即更新建议状态，并更新消息为已应用状态
    setAiSuggestions(prev => 
      prev.map((s, i) => i === index ? { 
        ...s, 
        accepted: true,
        message: getAcceptedMessage(s.type)
      } : s)
    )
  }

  // 获取应用后的消息
  const getAcceptedMessage = (type: string) => {
    switch (type) {
      case 'recurring':
        return '✅ 已设置为重复任务'
      case 'priority':
        return '✅ 已设为高优先级'
      case 'category':
        return '✅ 已更新任务分类'
      case 'time':
        return '✅ 已设置时间提醒'
      case 'reminder':
        return '✅ 已设置提醒时间'
      default:
        return '✅ 建议已应用'
    }
  }

  // 拒绝AI建议
  const dismissSuggestion = (index: number) => {
    setAiSuggestions(prev => prev.filter((_, i) => i !== index))
  }

  const handleAIDecompose = async () => {
    if (!task.title.trim()) return
    
    setShowAIDecompose(true)
    try {
      const result = await aiAPI.decomposeTask(task.title, task.description)
      if (result.success && result.subtasks) {
        console.log('AI任务分解结果:', result.subtasks)
        // 将AI分解的子任务添加到当前子任务列表
        const newSubtasks = result.subtasks.map((st: any) => ({
          title: st.title || st,
          completed: false
        }))
        setSubtasks([...subtasks, ...newSubtasks])
      } else {
        console.warn('AI任务分解失败:', result.message)
      }
    } catch (error) {
      console.error('AI任务分解出错:', error)
    } finally {
      setTimeout(() => {
        setShowAIDecompose(false)
      }, 1000)
    }
  }

  const priorities = [
    { value: 'P0', label: '紧急', color: 'text-error' },
    { value: 'P1', label: '高', color: 'text-warning' },
    { value: 'P2', label: '中', color: 'text-primary' },
    { value: 'P3', label: '低', color: 'text-text-secondary' }
  ]

  const categories = [
    { value: 'work', label: '工作', icon: '💼' },
    { value: 'personal', label: '个人', icon: '👤' },
    { value: 'learning', label: '学习', icon: '📚' },
    { value: 'health', label: '健康', icon: '🏃' },
    { value: 'other', label: '其他', icon: '📝' }
  ]

  return (
    <div className="min-h-screen bg-theme-bg-secondary">
      {/* 顶部导航 */}
      <div className="sticky top-0 z-10 bg-theme-bg/95 backdrop-blur-sm border-b border-theme-border/60 shadow-sm">
        <div className="flex items-center justify-between px-4 sm:px-6 py-4">
          <button
            onClick={() => navigate('/')}
            className="p-2 text-theme-text-secondary hover:text-theme-text hover:bg-theme-bg-tertiary rounded-lg transition-all touch-manipulation"
          >
            <ArrowLeft size={20} />
          </button>
          <h1 className="text-lg font-semibold text-theme-text">新任务</h1>
          <div className="flex items-center gap-2">
            {!isMinimalMode && (
              <button
                onClick={() => setIsMinimalMode(true)}
                className="px-3 py-1.5 text-xs text-theme-text-secondary hover:text-theme-text hover:bg-theme-bg-tertiary rounded-lg transition-all"
                title="切换到极简模式"
              >
                极简
              </button>
            )}
            <button
              onClick={handleSave}
              disabled={!task.title.trim()}
              className="px-6 py-2.5 bg-blue-600 text-white rounded-xl font-semibold hover:bg-blue-700 transition-all disabled:bg-slate-300 disabled:cursor-not-allowed shadow-lg text-sm"
            >
              创建任务
            </button>
          </div>
        </div>
      </div>

      <div className="px-4 sm:px-6 pb-6">
        {isMinimalMode ? (
          /* 极简模式界面 */
          <div className="max-w-2xl mx-auto space-y-4 sm:space-y-6 pt-4 sm:pt-6">
            {/* 主要输入区域 */}
            <div className="bg-theme-bg rounded-2xl sm:rounded-3xl border border-theme-border/60 p-4 sm:p-6 lg:p-8 shadow-lg">
              <div className="space-y-4 sm:space-y-6">
                {/* 任务标题输入 */}
                <div>
                  <div className="relative">
                    <input
                      type="text"
                      value={task.title}
                      onChange={(e) => setTask(prev => ({ ...prev, title: e.target.value }))}
                      onBlur={handleSmartParse}
                      onKeyPress={handleKeyPress}
                      placeholder="输入任务，例如：明天下午3点开会（按回车键智能解析）"
                      className="w-full px-4 sm:px-6 py-3 sm:py-4 text-lg sm:text-xl bg-theme-bg-secondary border-2 border-theme-border rounded-xl sm:rounded-2xl text-theme-text placeholder-slate-400 focus:outline-none focus:ring-0 focus:border-blue-500 focus:bg-theme-bg transition-all pr-12 sm:pr-14"
                      autoFocus
                    />
                    <button
                      onClick={handleSmartParse}
                      disabled={isAIParsing}
                      className={`absolute right-3 sm:right-4 top-1/2 -translate-y-1/2 p-1.5 sm:p-2 rounded-lg sm:rounded-xl transition-all disabled:cursor-not-allowed ${
                        isAIParsing 
                          ? 'text-blue-500 bg-blue-100 animate-pulse' 
                          : 'text-blue-600 hover:bg-blue-50 hover:text-blue-700'
                      }`}
                      title={isAIParsing ? "AI正在解析..." : "AI智能解析（按回车键）"}
                    >
                      <Bot size={18} className={isAIParsing ? "animate-spin" : ""} />
                    </button>
                  </div>
                  {/* AI解析状态提示 */}
                  {aiParsingStatus && (
                    <div className="mt-3 px-4 py-2 bg-blue-50 border border-blue-200 rounded-xl">
                      <p className="text-sm text-blue-700 flex items-center gap-2">
                        <Bot size={16} className="animate-pulse" />
                        {aiParsingStatus}
                      </p>
                    </div>
                  )}
                  
                  <p className="text-sm text-theme-text-muted mt-3 flex items-center gap-2 px-2">
                    <span className="text-base">💡</span>
                    输入自然语言，AI会自动解析时间、优先级等信息
                  </p>
                </div>

                {/* 子任务管理卡片 */}
                <div className="bg-theme-bg rounded-xl sm:rounded-2xl border border-theme-border/60 p-4 sm:p-5 shadow-sm">
                                <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-4">
                <div className="flex items-center gap-3">
                  <h3 className="text-sm font-semibold text-theme-text flex items-center gap-2">
                    <div className="w-1 h-4 bg-purple-500 rounded-full"></div>
                    子任务
                  </h3>
                  {/* AI分解状态 - 与子任务标题在同一行 */}
                  {showAIDecompose && (
                    <div className="flex items-center gap-2 text-indigo-700 text-xs sm:text-sm font-medium">
                      <div className="animate-spin">
                        <Bot size={12} />
                      </div>
                      <span className="whitespace-nowrap overflow-hidden text-ellipsis">AI正在分析任务并生成子任务...</span>
                    </div>
                  )}
                </div>
                <div className="flex items-center gap-2">
                  <span className="px-2 py-1 bg-theme-bg-tertiary text-theme-text-secondary text-xs rounded-full font-semibold">
                    {subtasks.filter(st => st.completed).length}/{subtasks.length} 已完成
                  </span>
                  <button
                    onClick={handleAIDecompose}
                    disabled={!task.title.trim() || showAIDecompose}
                    className="px-2 sm:px-3 py-1.5 text-xs bg-indigo-100 text-indigo-700 hover:bg-indigo-200 rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-1"
                    title="AI智能分解任务"
                  >
                    <Bot size={12} className={showAIDecompose ? "animate-spin" : ""} />
                    <span className="hidden sm:inline">AI分解</span>
                    <span className="sm:hidden">AI</span>
                  </button>
                </div>
              </div>

                  {/* 子任务列表 */}
                  {subtasks.length > 0 && (
                    <div className="space-y-2 mb-4 max-h-32 sm:max-h-40 overflow-y-auto">
                      {subtasks.map((subtask, index) => (
                        <div key={index} className="flex items-center gap-2 sm:gap-3 p-2 sm:p-3 bg-theme-bg-secondary rounded-lg">
                          <button
                            onClick={() => toggleSubtask(index)}
                            className="flex-shrink-0"
                          >
                            {subtask.completed ? (
                              <CheckCircle size={16} className="text-green-500" />
                            ) : (
                              <Circle size={16} className="text-slate-400" />
                            )}
                          </button>
                          <span className={`text-xs sm:text-sm flex-1 ${
                            subtask.completed ? 'line-through text-theme-text-muted' : 'text-theme-text'
                          }`}>
                            {subtask.title}
                          </span>
                          <button
                            onClick={() => removeSubtask(index)}
                            className="p-1 text-slate-400 hover:text-red-500 hover:bg-red-50 rounded transition-all"
                          >
                            <Trash2 size={10} className="sm:w-3 sm:h-3" />
                          </button>
                        </div>
                      ))}
                    </div>
                  )}

                  {/* 添加子任务输入框 */}
                  <div className="flex items-center gap-2 sm:gap-3 p-2 sm:p-3 bg-theme-bg-secondary rounded-lg sm:rounded-xl">
                    <Circle size={14} className="text-slate-400 flex-shrink-0 sm:w-4 sm:h-4" />
                    <input
                      type="text"
                      value={newSubtaskTitle}
                      onChange={(e) => setNewSubtaskTitle(e.target.value)}
                      placeholder="添加子任务..."
                      className="flex-1 text-xs sm:text-sm bg-transparent border-none outline-none placeholder-slate-400"
                      onKeyPress={(e) => {
                        if (e.key === 'Enter') {
                          addSubtask()
                        }
                      }}
                    />
                    <button
                      onClick={addSubtask}
                      disabled={!newSubtaskTitle.trim()}
                      className="p-1.5 sm:p-2 text-blue-600 hover:bg-blue-50 rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      <Plus size={14} className="sm:w-4 sm:h-4" />
                    </button>
                  </div>

                  {/* 子任务进度条 */}
                  {subtasks.length > 0 && (
                    <div className="mt-4">
                      <div className="flex items-center justify-between mb-2">
                        <span className="text-xs text-theme-text-secondary">完成进度</span>
                        <span className="text-xs font-semibold text-theme-text">
                          {Math.round((subtasks.filter(st => st.completed).length / subtasks.length) * 100)}%
                        </span>
                      </div>
                      <div className="w-full bg-theme-bg-tertiary rounded-full h-2">
                        <div 
                          className="bg-gradient-to-r from-blue-500 to-purple-500 h-2 rounded-full transition-all duration-300"
                          style={{ 
                            width: `${(subtasks.filter(st => st.completed).length / subtasks.length) * 100}%` 
                          }}
                        />
                      </div>
                    </div>
                  )}
                </div>

                {/* 快速日期选择 */}
                <div className="space-y-3">
                  <label className="text-sm font-semibold text-theme-text flex items-center gap-2">
                    <Calendar size={16} className="text-blue-500" />
                    截止时间
                  </label>
                  <div className="grid grid-cols-2 sm:grid-cols-4 gap-2 sm:gap-3">
                    {(() => {
                      const today = new Date().toISOString().split('T')[0]
                      const tomorrow = new Date(Date.now() + 24*60*60*1000).toISOString().split('T')[0]
                      const nextWeek = new Date(Date.now() + 7*24*60*60*1000).toISOString().split('T')[0]
                      
                      return [
                        { key: 'today', label: '今天', active: task.dueDate === today },
                        { key: 'tomorrow', label: '明天', active: task.dueDate === tomorrow },
                        { key: 'week', label: '下周', active: task.dueDate === nextWeek },
                        { key: 'custom', label: '选择', active: task.dueDate && ![today, tomorrow, nextWeek].includes(task.dueDate) }
                      ].map((option) => (
                        <button
                          key={option.key}
                          onClick={() => {
                            console.log('点击日期按钮:', option.key)
                            if (option.key === 'custom') {
                              // 显示自定义日期选择器
                              setShowCustomDatePicker(true)
                            } else {
                              setQuickDate(option.key as 'today' | 'tomorrow' | 'week')
                            }
                          }}
                          className={`px-3 sm:px-4 py-2 sm:py-3 rounded-lg sm:rounded-xl border-2 font-semibold transition-all text-xs sm:text-sm ${
                            option.active
                              ? 'border-blue-500 bg-blue-500 text-white shadow-lg'
                              : 'border-theme-border bg-theme-bg-secondary text-theme-text hover:border-blue-300 hover:bg-blue-50'
                          }`}
                        >
                          {option.label}
                        </button>
                      ))
                    })()}
                  </div>
                  
                  {/* 自定义日期选择器 */}
                  {showCustomDatePicker && (
                    <div className="p-4 bg-purple-50 rounded-xl border border-purple-200">
                      <div className="flex items-center gap-3 mb-3">
                        <span className="text-sm font-medium text-purple-900">选择日期：</span>
                        <input
                          type="date"
                          value={task.dueDate}
                          onChange={(e) => {
                            setTask(prev => ({ ...prev, dueDate: e.target.value }))
                          }}
                          className="px-3 py-2 bg-white border border-purple-200 rounded-lg text-purple-900 text-sm focus:outline-none focus:ring-2 focus:ring-purple-500/20 focus:border-purple-500"
                        />
                      </div>
                      <div className="flex gap-2">
                        <button
                          onClick={() => setShowCustomDatePicker(false)}
                          className="px-3 py-1 text-xs bg-purple-200 text-purple-800 rounded-full hover:bg-purple-300 transition-colors"
                        >
                          确定
                        </button>
                        <button
                          onClick={() => {
                            setTask(prev => ({ ...prev, dueDate: '' }))
                            setShowCustomDatePicker(false)
                          }}
                          className="px-3 py-1 text-xs bg-gray-200 text-gray-600 rounded-full hover:bg-gray-300 transition-colors"
                        >
                          清除
                        </button>
                      </div>
                    </div>
                  )}

                  {/* 时间选择器 */}
                  {(task.dueDate || showTimeSelector) && (
                    <div className="flex items-center gap-3 p-4 bg-blue-50 rounded-xl border border-blue-200">
                      <span className="text-sm font-medium text-blue-900">具体时间：</span>
                      <input
                        type="time"
                        value={task.dueTime}
                        onChange={(e) => setTask(prev => ({ ...prev, dueTime: e.target.value }))}
                        className="px-3 py-2 bg-white border border-blue-200 rounded-lg text-blue-900 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500"
                      />
                      <span className="text-xs text-blue-700">可选</span>
                    </div>
                  )}

                  {/* 显示选择的日期时间 */}
                  {task.dueDate && (
                    <div className="p-3 bg-green-50 rounded-xl border border-green-200">
                      <p className="text-sm text-green-800 font-medium flex items-center gap-2">
                        <Calendar size={16} />
                        截止时间：{task.dueDate} {task.dueTime && task.dueTime}
                        {task.dueTime && (
                          <span className="text-xs bg-green-200 px-2 py-1 rounded-full">
                            将提前 {task.reminderMinutes < 60 ? `${task.reminderMinutes}分钟` : `${Math.floor(task.reminderMinutes/60)}小时`} 提醒
                          </span>
                        )}
                      </p>
                    </div>
                  )}

                  {/* 任务配置预览 */}
                  {(task.priority !== 'P2' || task.category !== 'work' || task.isRecurring) && (
                    <div className="p-3 bg-blue-50 rounded-xl border border-blue-200">
                      <p className="text-xs text-blue-600 font-medium mb-1">当前配置：</p>
                      <div className="flex flex-wrap gap-2 text-xs">
                        {task.priority !== 'P2' && (
                          <span className="bg-blue-200 text-blue-800 px-2 py-1 rounded-full">
                            优先级: {task.priority === 'P1' ? '高' : task.priority === 'P3' ? '低' : task.priority}
                          </span>
                        )}
                        {task.category !== 'work' && (
                          <span className="bg-blue-200 text-blue-800 px-2 py-1 rounded-full">
                            分类: {task.category === 'learning' ? '学习' : task.category === 'health' ? '健康' : task.category === 'personal' ? '个人' : task.category}
                          </span>
                        )}
                        {task.isRecurring && (
                          <span className="bg-blue-200 text-blue-800 px-2 py-1 rounded-full">
                            重复: {task.recurringType === 'daily' ? '每天' : task.recurringType === 'weekly' ? '每周' : task.recurringType}
                          </span>
                        )}
                      </div>
                    </div>
                  )}
                </div>
              </div>
            </div>

            {/* AI建议卡片 */}
            {aiSuggestions.length > 0 && (
              <div className="space-y-3">
                {aiSuggestions.map((suggestion, index) => (
                  <div 
                    key={index}
                    className={`p-4 rounded-2xl border transition-all ${
                      suggestion.accepted 
                        ? 'bg-green-50 border-green-200' 
                        : 'bg-amber-50 border-amber-200 hover:bg-amber-100'
                    }`}
                  >
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-3">
                        <div className="p-2 bg-white rounded-lg shadow-sm">
                          {suggestion.type === 'recurring' && '🔄'}
                          {suggestion.type === 'priority' && '⚡'}
                          {suggestion.type === 'category' && '📁'}
                          {suggestion.type === 'time' && '⏰'}
                          {suggestion.type === 'reminder' && '🔔'}
                        </div>
                        <div>
                          <p className="text-sm font-medium text-amber-900">
                            {suggestion.accepted ? '✅ 已应用' : '💡 AI建议'}
                          </p>
                          <p className="text-sm text-amber-800">{suggestion.message}</p>
                          {suggestion.accepted && (
                            <p className="text-xs text-green-600 mt-1">
                              {suggestion.type === 'recurring' && `重复类型: ${task.recurringType === 'daily' ? '每天' : task.recurringType}`}
                              {suggestion.type === 'priority' && `优先级: ${task.priority === 'P1' ? '高优先级' : task.priority}`}
                              {suggestion.type === 'category' && `分类: ${task.category === 'work' ? '工作' : task.category === 'learning' ? '学习' : task.category === 'health' ? '健康' : task.category}`}
                              {suggestion.type === 'time' && `时间: ${task.dueTime}`}
                              {suggestion.type === 'reminder' && `提醒: 提前${task.reminderMinutes}分钟`}
                            </p>
                          )}
                        </div>
                      </div>
                      {!suggestion.accepted && (
                        <div className="flex items-center gap-2">
                          <button
                            onClick={() => acceptSuggestion(index)}
                            className="px-3 py-1.5 bg-amber-600 text-white text-xs rounded-lg hover:bg-amber-700 transition-all font-medium"
                          >
                            应用
                          </button>
                          <button
                            onClick={() => dismissSuggestion(index)}
                            className="px-3 py-1.5 bg-white text-amber-600 text-xs rounded-lg border border-amber-300 hover:bg-amber-50 transition-all font-medium"
                          >
                            忽略
                          </button>
                        </div>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            )}

            {/* 高级选项切换 */}
            <div className="text-center">
              <button
                onClick={() => setIsMinimalMode(false)}
                className="px-6 py-3 text-theme-text-secondary hover:text-theme-text hover:bg-theme-bg-tertiary rounded-xl transition-all text-sm font-medium border border-theme-border hover:border-theme-border-hover"
              >
                需要更多设置？点击展开高级选项
              </button>
            </div>
          </div>
        ) : (
          /* 原有的完整界面 */
          <div className="space-y-4 pt-4">
        {/* 智能输入框卡片 */}
        <div className="bg-theme-bg rounded-2xl border border-theme-border/60 p-5 shadow-sm">
          <h3 className="text-sm font-semibold text-theme-text mb-4 flex items-center gap-2">
            <div className="w-1 h-4 bg-blue-500 rounded-full"></div>
            任务标题
          </h3>
          <div className="relative">
            <input
              type="text"
              value={task.title}
              onChange={(e) => setTask(prev => ({ ...prev, title: e.target.value }))}
              onBlur={handleSmartParse}
              onKeyPress={handleKeyPress}
              placeholder="输入任务，例如：每天下班记得要打卡（按回车键智能解析）"
              className="w-full px-4 py-3 bg-theme-bg-secondary border border-theme-border rounded-xl text-theme-text placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 focus:bg-theme-bg transition-all pr-12"
            />
            <button
              onClick={handleSmartParse}
              disabled={isAIParsing}
              className={`absolute right-3 top-1/2 -translate-y-1/2 p-2 rounded-lg transition-all disabled:cursor-not-allowed ${
                isAIParsing 
                  ? 'text-blue-500 bg-blue-100 animate-pulse' 
                  : 'text-blue-600 hover:bg-blue-50 hover:text-blue-700'
              }`}
              title={isAIParsing ? "AI正在解析..." : "AI智能解析（按回车键）"}
            >
              <Bot size={16} className={isAIParsing ? "animate-spin" : ""} />
            </button>
          </div>
          
          {/* AI解析状态提示 */}
          {aiParsingStatus && (
            <div className="mt-3 px-3 py-2 bg-blue-50 border border-blue-200 rounded-lg">
              <p className="text-xs text-blue-700 flex items-center gap-2">
                <Bot size={14} className="animate-pulse" />
                {aiParsingStatus}
              </p>
            </div>
          )}
          
          {/* 智能提示已移至AI建议系统 - 避免硬匹配重复 */}
          <p className="text-xs text-theme-text-muted mt-3 flex items-center gap-2">
            <span className="text-base">💡</span>
            输入自然语言，AI会自动解析日期、优先级等信息
          </p>
        </div>

        {/* 详细信息面板 */}
        <div className="bg-theme-bg rounded-2xl border border-theme-border/60 shadow-sm overflow-hidden">
          <button
            onClick={() => setShowDetails(!showDetails)}
            className="flex items-center justify-between w-full p-5 hover:bg-theme-bg-secondary transition-colors"
          >
            <div className="flex items-center gap-2">
              <div className="w-1 h-4 bg-green-500 rounded-full"></div>
              <span className="text-sm font-semibold text-theme-text">详细信息</span>
            </div>
            <span className={`transform transition-transform text-slate-400 ${showDetails ? 'rotate-180' : ''}`}>
              ▼
            </span>
          </button>

          {showDetails && (
            <div className="px-5 pb-5 space-y-5 border-t border-slate-100">
              {/* 日期和时间选择 */}
              <div className="space-y-3">
                <label className="flex items-center text-sm font-semibold text-theme-text">
                  <Calendar size={16} className="mr-2 text-theme-text-muted" />
                  截止时间
                </label>
                <div className="grid grid-cols-2 gap-3">
                  <div>
                    <label className="text-xs text-theme-text-muted mb-1 block">日期</label>
                    <input
                      type="date"
                      value={task.dueDate}
                      onChange={(e) => setTask(prev => ({ ...prev, dueDate: e.target.value }))}
                      className="w-full px-3 py-2 bg-theme-bg-secondary border border-theme-border rounded-lg text-theme-text text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 focus:bg-theme-bg transition-all"
                    />
                  </div>
                  <div>
                    <label className="text-xs text-theme-text-muted mb-1 block">时间</label>
                    <input
                      type="time"
                      value={task.dueTime}
                      onChange={(e) => setTask(prev => ({ ...prev, dueTime: e.target.value }))}
                      className="w-full px-3 py-2 bg-theme-bg-secondary border border-theme-border rounded-lg text-theme-text text-sm focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 focus:bg-theme-bg transition-all"
                      placeholder="可选"
                    />
                  </div>
                </div>
                {task.dueTime && (
                  <p className="text-xs text-blue-600 flex items-center gap-1">
                    ⏰ 将在 {task.dueDate} {task.dueTime} 提醒您
                  </p>
                )}
              </div>

              {/* 提醒设置 */}
              {task.dueDate && (
                <div className="space-y-3">
                  <label className="flex items-center text-sm font-semibold text-theme-text">
                    <Calendar size={16} className="mr-2 text-theme-text-muted" />
                    提醒设置
                  </label>
                  <div className="space-y-2">
                    <label className="text-xs text-theme-text-muted block">提前多长时间提醒</label>
                    <div className="grid grid-cols-2 gap-2">
                      {[5, 15, 30, 60, 120, 1440].map((minutes) => (
                        <button
                          key={minutes}
                          onClick={() => setTask(prev => ({ ...prev, reminderMinutes: minutes }))}
                          className={`px-3 py-2 rounded-lg text-sm font-medium transition-all ${
                            task.reminderMinutes === minutes
                              ? 'bg-blue-500 text-white shadow-md'
                              : 'bg-theme-bg-secondary border border-theme-border text-theme-text hover:bg-blue-50 hover:border-blue-300'
                          }`}
                        >
                          {minutes < 60 ? `${minutes}分钟` : minutes === 60 ? '1小时' : minutes === 120 ? '2小时' : '1天'}
                        </button>
                      ))}
                    </div>
                    <p className="text-xs text-theme-text-muted">
                      💡 将在截止时间前 {task.reminderMinutes < 60 ? `${task.reminderMinutes}分钟` : task.reminderMinutes === 60 ? '1小时' : task.reminderMinutes === 120 ? '2小时' : '1天'} 发送通知
                    </p>
                  </div>
                </div>
              )}

              {/* 优先级选择 */}
              <div className="space-y-3">
                <label className="flex items-center text-sm font-semibold text-theme-text">
                  <Flag size={16} className="mr-2 text-theme-text-muted" />
                  优先级
                </label>
                <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
                  {priorities.map((priority) => (
                    <button
                      key={priority.value}
                      onClick={() => setTask(prev => ({ ...prev, priority: priority.value as any }))}
                      className={`px-3 py-2.5 rounded-xl border font-medium transition-all ${
                        task.priority === priority.value
                          ? 'border-blue-500 bg-blue-500 text-white shadow-sm'
                          : 'border-theme-border bg-theme-bg-secondary text-theme-text-secondary hover:border-blue-300 hover:bg-blue-50'
                      }`}
                    >
                      {priority.label}
                    </button>
                  ))}
                </div>
              </div>

              {/* 分类选择 */}
              <div className="space-y-3">
                <label className="flex items-center text-sm font-semibold text-theme-text">
                  <Folder size={16} className="mr-2 text-theme-text-muted" />
                  分类
                </label>
                <div className="grid grid-cols-3 sm:grid-cols-5 gap-3">
                  {categories.map((category) => (
                    <button
                      key={category.value}
                      onClick={() => setTask(prev => ({ ...prev, category: category.value as any }))}
                      className={`p-3 rounded-xl border transition-all ${
                        task.category === category.value
                          ? 'border-blue-500 bg-blue-500 text-white shadow-sm'
                          : 'border-theme-border bg-theme-bg-secondary text-theme-text-secondary hover:border-blue-300 hover:bg-blue-50'
                      }`}
                    >
                      <div className="text-lg mb-1">{category.icon}</div>
                      <div className="text-xs font-medium">{category.label}</div>
                    </button>
                  ))}
                </div>
              </div>

              {/* 标签输入 */}
              <div className="space-y-3">
                <label className="flex items-center text-sm font-semibold text-theme-text">
                  <Tag size={16} className="mr-2 text-theme-text-muted" />
                  标签
                </label>
                <div className="space-y-3">
                  <div className="flex flex-wrap gap-2">
                    {task.tags.map((tag, index) => (
                      <span
                        key={index}
                        className="px-3 py-1.5 bg-blue-100 text-blue-700 rounded-full text-sm font-medium flex items-center gap-1"
                      >
                        {tag}
                        <button
                          onClick={() => setTask(prev => ({ 
                            ...prev, 
                            tags: prev.tags.filter((_, i) => i !== index) 
                          }))}
                          className="text-blue-500 hover:text-blue-700 hover:bg-blue-200 rounded-full p-0.5 transition-all"
                        >
                          ×
                        </button>
                      </span>
                    ))}
                  </div>
                  <input
                    type="text"
                    placeholder="添加标签，按回车确认"
                    className="w-full px-4 py-3 bg-theme-bg-secondary border border-theme-border rounded-xl text-theme-text placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 focus:bg-theme-bg transition-all"
                    onKeyPress={(e) => {
                      if (e.key === 'Enter' && e.currentTarget.value.trim()) {
                        setTask(prev => ({ 
                          ...prev, 
                          tags: [...prev.tags, e.currentTarget.value.trim()] 
                        }))
                        e.currentTarget.value = ''
                      }
                    }}
                  />
                </div>
              </div>

              {/* 备注 */}
              <div className="space-y-3">
                <label className="text-sm font-semibold text-theme-text">备注</label>
                <textarea
                  value={task.notes}
                  onChange={(e) => setTask(prev => ({ ...prev, notes: e.target.value }))}
                  placeholder="添加备注..."
                  rows={3}
                  className="w-full px-4 py-3 bg-theme-bg-secondary border border-theme-border rounded-xl text-theme-text placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 focus:bg-theme-bg transition-all resize-none"
                />
              </div>

              {/* 重复任务设置 */}
              <div className="space-y-3">
                <div className="flex items-center justify-between">
                  <label className="text-sm font-semibold text-theme-text">重复任务</label>
                  <button
                    type="button"
                    onClick={() => setTask(prev => ({ ...prev, isRecurring: !prev.isRecurring }))}
                    className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
                      task.isRecurring ? 'bg-blue-600' : 'bg-slate-200'
                    }`}
                  >
                    <span
                      className={`inline-block h-4 w-4 transform rounded-full bg-theme-bg transition-transform ${
                        task.isRecurring ? 'translate-x-6' : 'translate-x-1'
                      }`}
                    />
                  </button>
                </div>
                
                {task.isRecurring && (
                  <div className="space-y-3 p-3 bg-blue-50 rounded-xl border border-blue-200">
                    <div>
                      <label className="text-xs font-medium text-blue-900 mb-2 block">重复频率</label>
                      <div className="grid grid-cols-2 gap-2">
                        {[
                          { value: 'daily', label: '每天', icon: '📅' },
                          { value: 'weekly', label: '每周', icon: '📆' },
                          { value: 'monthly', label: '每月', icon: '📋' },
                          { value: 'yearly', label: '每年', icon: '🗓️' }
                        ].map((option) => (
                          <button
                            key={option.value}
                            type="button"
                            onClick={() => setTask(prev => ({ ...prev, recurringType: option.value as any }))}
                            className={`p-2 rounded-lg border font-medium transition-all text-sm ${
                              task.recurringType === option.value
                                ? 'border-blue-500 bg-blue-500 text-white shadow-sm'
                                : 'border-blue-200 bg-theme-bg text-blue-700 hover:border-blue-300 hover:bg-blue-50'
                            }`}
                          >
                            <div className="flex items-center justify-center gap-1">
                              <span>{option.icon}</span>
                              <span>{option.label}</span>
                            </div>
                          </button>
                        ))}
                      </div>
                    </div>
                    
                    {task.recurringPattern && (
                      <div>
                        <label className="text-xs font-medium text-blue-900 mb-2 block">重复模式</label>
                        <div className="p-2 bg-theme-bg rounded-lg border border-blue-200 text-sm text-blue-800">
                          {getRecurringPatternLabel(task.recurringPattern)}
                        </div>
                      </div>
                    )}
                  </div>
                )}
              </div>
            </div>
          )}
        </div>

        {/* 子任务管理 */}
        <div className="bg-theme-bg rounded-2xl border border-theme-border/60 p-5 shadow-sm">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-sm font-semibold text-theme-text flex items-center gap-2">
              <div className="w-1 h-4 bg-purple-500 rounded-full"></div>
              子任务
            </h3>
            <span className="px-2 py-1 bg-theme-bg-tertiary text-theme-text-secondary text-xs rounded-full font-semibold">
              {subtasks.filter(st => st.completed).length}/{subtasks.length} 已完成
            </span>
          </div>
          
          {/* 添加子任务输入框 */}
          <div className="flex items-center gap-3 mb-4 p-3 bg-theme-bg-secondary rounded-xl">
            <Circle size={18} className="text-slate-400 flex-shrink-0" />
            <input
              type="text"
              value={newSubtaskTitle}
              onChange={(e) => setNewSubtaskTitle(e.target.value)}
              placeholder="添加子任务..."
              className="flex-1 text-sm bg-transparent border-none outline-none placeholder-slate-400"
              onKeyPress={(e) => {
                if (e.key === 'Enter') {
                  addSubtask()
                }
              }}
            />
            <button
              onClick={addSubtask}
              disabled={!newSubtaskTitle.trim()}
              className="p-2 text-blue-600 hover:bg-blue-50 rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <Plus size={16} />
            </button>
          </div>

          {/* 子任务列表 */}
          {subtasks.length > 0 && (
            <div className="space-y-2 mb-4">
              {subtasks.map((subtask, index) => (
                <div key={index} className="flex items-center gap-3 p-3 bg-theme-bg-secondary rounded-xl group hover:bg-theme-bg-tertiary transition-colors">
                  <button
                    onClick={() => toggleSubtask(index)}
                    className="flex-shrink-0 hover:scale-110 transition-all"
                  >
                    {subtask.completed ? (
                      <CheckCircle size={18} className="text-green-500" />
                    ) : (
                      <Circle size={18} className="text-slate-400 hover:text-blue-500" />
                    )}
                  </button>
                  <span className={`flex-1 text-sm font-medium ${
                    subtask.completed ? 'line-through text-theme-text-muted' : 'text-theme-text'
                  }`}>
                    {subtask.title}
                  </span>
                  <button
                    onClick={() => removeSubtask(index)}
                    className="opacity-0 group-hover:opacity-100 p-1.5 text-slate-400 hover:text-red-500 hover:bg-red-50 rounded-lg transition-all"
                  >
                    <Trash2 size={14} />
                  </button>
                </div>
              ))}
            </div>
          )}

          {/* 子任务进度条 */}
          {subtasks.length > 0 && (
            <div className="pt-4 border-t border-theme-border">
              <div className="flex items-center justify-between text-xs text-theme-text-secondary mb-2">
                <span className="font-medium">完成进度</span>
                <span className="font-semibold">{Math.round((subtasks.filter(st => st.completed).length / subtasks.length) * 100)}%</span>
              </div>
              <div className="w-full bg-slate-200 rounded-full h-2.5">
                <div 
                  className="bg-gradient-to-r from-purple-500 to-purple-600 h-2.5 rounded-full transition-all duration-500 ease-out"
                  style={{ 
                    width: `${(subtasks.filter(st => st.completed).length / subtasks.length) * 100}%` 
                  }}
                ></div>
              </div>
            </div>
          )}
        </div>

        {/* AI操作区 */}
        <div className="bg-theme-bg rounded-2xl border border-theme-border/60 p-5 shadow-sm">
          <div className="space-y-4">
            <div className="flex items-center gap-2 mb-3">
              <div className="w-1 h-4 bg-indigo-500 rounded-full"></div>
              <Bot size={16} className="text-indigo-600" />
              <h3 className="text-sm font-semibold text-theme-text">AI智能助手</h3>
            </div>
            
            <button
              onClick={handleAIDecompose}
              disabled={showAIDecompose || !task.title.trim()}
              className="w-full p-4 bg-gradient-to-r from-indigo-50 to-purple-50 border border-indigo-200 rounded-xl text-indigo-700 hover:from-indigo-100 hover:to-purple-100 hover:border-indigo-300 transition-all disabled:opacity-50 disabled:cursor-not-allowed shadow-sm"
            >
              <div className="flex items-center justify-center gap-3">
                <div className="p-2 bg-theme-bg rounded-lg shadow-sm">
                  <Bot size={18} className="text-indigo-600" />
                </div>
                <div className="text-left">
                  <div className="font-semibold">AI分解任务</div>
                  <div className="text-xs text-indigo-600">自动将复杂任务分解为子任务</div>
                </div>
              </div>
            </button>
            
            {/* AI智能示例 */}
            <div className="p-3 bg-theme-bg-secondary rounded-xl border border-theme-border">
              <div className="text-xs font-medium text-theme-text-secondary mb-2">🤖 AI智能示例：</div>
              <div className="space-y-1 text-xs text-theme-text-secondary">
                <div>• "每天下班记得要打卡" → 自动识别重复任务</div>
                <div>• "明天下午3点开会" → 解析时间和优先级</div>
                <div>• "准备年度总结报告" → 生成子任务步骤</div>
              </div>
            </div>
            
            {showAIDecompose && (
              <div className="p-4 bg-indigo-50 border border-indigo-200 rounded-xl">
                <div className="flex items-center gap-3 text-indigo-700">
                  <div className="animate-spin">
                    <Bot size={16} />
                  </div>
                  <span className="text-sm font-medium">AI正在分析任务并生成子任务...</span>
                </div>
              </div>
            )}
          </div>
        </div>
          </div>
        )}
      </div>
    </div>
  )
}
